import { nextTick } from 'vue';
import _ from 'lodash';

// 重置class
const setLayout = (customClass = 'layout-content-custom', targetClass = 'layout-content') => {
    nextTick(() => {
        document.querySelector(`.${targetClass}`)?.classList?.add(customClass);
    });
};

// 卸载class
const resetLayout = (customClass = 'layout-content-custom', targetClass = 'layout-content') => {
    document.querySelector(`.${targetClass}`) &&
        document.querySelector(`.${targetClass}`)?.classList?.remove(customClass);
};

// 获取table高度
const getTableHeight = (parentClass, heightTarget, bottomClass) => {
    try {
        const parent = document.querySelector(`.${parentClass}`);
        const getPxNum = val => val.replace(/px/i, '') / 1;
        const allHeight = (el, propertyList) => {
            const parentStyle = window.getComputedStyle(el, null);
            return propertyList.reduce((acc, cur) => {
                return acc + getPxNum(parentStyle.getPropertyValue(cur));
            }, 0);
        };
        const parentPaddingBottom = allHeight(parent, ['padding-bottom']);
        const parentInnerHeight = parent.clientHeight - parentPaddingBottom;
        // .el-table 必须是parentClass元素下直接子元素，且只能有一个
        const table = document.querySelector(`.${parentClass} > .el-table`);
        const tableInnerTop = table.offsetTop - parent.offsetTop;
        const tableHeight = parentInnerHeight - tableInnerTop;
        const bottom = document.querySelector(`.${bottomClass}`);
        let bottomHeight = 0;
        if (bottom) {
            bottomHeight =
                allHeight(bottom, ['padding-top', 'padding-bottom', 'margin-top', 'margin-bottom']) +
                bottom.clientHeight;
        }
        heightTarget.value = tableHeight - bottomHeight;
    } catch {
        heightTarget.value = 300;
    }
};

// resize回调
const resizeCallback = (parentClass, heightTarget, bottomClass) => {
    return _.debounce(() => {
        getTableHeight(parentClass, heightTarget, bottomClass);
    }, 500);
};
// 监听窗口变化
const resizeTableHeight = (parentClass, heightTarget, bottomClass) => {
    getTableHeight(parentClass, heightTarget, bottomClass);
    window.addEventListener('resize', resizeCallback(parentClass, heightTarget, bottomClass), false);
};
const resizeTableRemove = () => {
    window.removeEventListener('resize', resizeCallback);
};

const useDocumentVisibility = (type = 'add', fn) => {
    // 监听/移除页面可见
    document[`${type}EventListener`]('visibilitychange', fn);
};

export { setLayout, resetLayout, getTableHeight, resizeTableHeight, resizeTableRemove, useDocumentVisibility };
